//
//  KoiBookSync.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 18.04.25.
//

import Foundation
class KoiBookSync : KoiDataSyncBase<AccountingBook> {
    
    private let detailDao = KoiAccountingDB.standard.getDetailDao()
    private let bookDao = KoiAccountingDB.standard.getBookDao()
    
    
    override var syncPref: String {
        return "sync:book:"
    }
    
    override func getPullResponse(offset: Int? = nil) -> Result<KoiSyncResponseData<AccountingBook>?, KoiNetError> {
        var params = ["last_sv": getLastSv()]
        if let offset = offset {
            params["offset"] = offset
        }
        return KoiNetBase.baseShared.requestAuth(
            path: "book/sync/pull",
            method: .post,
            parameters: params
        )
    }
    
    override func getPushResponse(list: Array<AccountingBook>, offset: Int) -> Result<KoiSyncResponseData<AccountingBook>?, KoiNetError> {
        var params = [String: Any]()
        params["list"] = list.jsonEncode()
        params["offset"] = offset
        return KoiNetBase.baseShared.requestAuth(
            path: "book/sync/push",
            method: .post,
            parameters: params
        )
    }
    
    override func getPushData(pageSize:Int, offset:Int) -> Array<AccountingBook> {
        return bookDao.getPushData(pageSize: pageSize, offset: offset, uid: uid)
    }
    
    override func updatePullData(list: Array<AccountingBook>, lastSv: Int) throws {
        // 拉回来的数据，默认值是 not sync ，需要手动设置为 synced
        var list = list
        for i in list.indices {
            list[i].dataFlag = DataFlag.synced.rawValue
            list[i].sv = lastSv
        }
        try bookDao.updateSync(books: list)
    }
    
    override func updatePushData(list: Array<AccountingBook>?, lastSv: Int) throws {
        guard var list = list else { return }
        for i in list.indices {
            list[i].dataFlag = DataFlag.synced.rawValue
            list[i].sv = lastSv
        }
        try bookDao.updateSync(books: list)
    }
}

